using Microsoft.EntityFrameworkCore;
using MediPlatform.Domain.Order;
using MediPlatform.Infeartructure;

namespace MediPlatform.Read.Api.Services
{
    public class MedicalOrderDataInitializer
    {
        private readonly MyDbContext _context;
        private readonly ILogger<MedicalOrderDataInitializer> _logger;

        public MedicalOrderDataInitializer(MyDbContext context, ILogger<MedicalOrderDataInitializer> logger)
        {
            _context = context;
            _logger = logger;
        }

        public async Task InitializeAsync()
        {
            try
            {
                // 检查是否已有数据
                var existingOrders = await _context.MedicalOrder.CountAsync();
                if (existingOrders > 0)
                {
                    _logger.LogInformation("药品订单表已有数据，跳过初始化");
                    return;
                }

                _logger.LogInformation("开始初始化药品订单数据");

                // 获取用户数据
                var users = await _context.User.Take(5).ToListAsync();
                if (!users.Any())
                {
                    _logger.LogWarning("没有找到用户数据，无法初始化药品订单");
                    return;
                }

                var orders = new List<MedicalOrder>();
                var orderItems = new List<MedicalOrderItem>();
                var logisticsTracking = new List<MedicalOrderLogisticsTracking>();

                // 生成订单数据
                for (int i = 1; i <= 50; i++)
                {
                    var user = users[i % users.Count];
                    var orderNo = $"MO{DateTime.Now:yyyyMMdd}{i:D4}";
                    // 使用多种状态：0-待支付, 1-已支付, 2-已确认, 3-已拣货, 4-已发货, 5-已签收, 6-已取消
                    var status = i % 7; // 0-6的状态
                    var createdAt = DateTime.Now.AddDays(-i % 30); // 最近30天内的订单

                    var order = new MedicalOrder
                    {
                        OrderNo = orderNo,
                        UserId = user.Id,
                        TotalAmount = 100 + (i * 10),
                        ActualAmount = 100 + (i * 10),
                        Status = status,
                        PaymentMethod = i % 2 == 0 ? "wechat" : "alipay",
                        PaymentTime = status > 0 ? createdAt.AddHours(1) : null,
                        DeliveryAddress = $"张三,13800138000,北京市朝阳区第{i}街道{i}号",
                        LogisticsCompany = status >= 4 ? "顺丰快递" : null,
                        TrackingNumber = status >= 4 ? $"SF{DateTime.Now:yyyyMMdd}{i:D6}" : null,
                        SignTime = status == 5 ? createdAt.AddDays(3) : null,
                        CreatedAt = createdAt,
                        UpdatedAt = createdAt
                    };

                    orders.Add(order);
                }

                // 保存订单
                await _context.MedicalOrder.AddRangeAsync(orders);
                await _context.SaveChangesAsync();

                // 生成订单商品数据
                var medicines = new[]
                {
                    new { Name = "阿莫西林胶囊", Spec = "0.25g*24粒", Price = 15.5m },
                    new { Name = "布洛芬片", Spec = "0.1g*20片", Price = 12.8m },
                    new { Name = "感冒灵颗粒", Spec = "10g*12袋", Price = 25.0m },
                    new { Name = "维生素C片", Spec = "0.1g*100片", Price = 18.5m },
                    new { Name = "板蓝根颗粒", Spec = "10g*20袋", Price = 22.0m }
                };

                foreach (var order in orders)
                {
                    var itemCount = Random.Shared.Next(1, 4); // 1-3个商品
                    for (int j = 0; j < itemCount; j++)
                    {
                        var medicine = medicines[Random.Shared.Next(medicines.Length)];
                        var quantity = Random.Shared.Next(1, 5);
                        var subtotal = medicine.Price * quantity;

                        var orderItem = new MedicalOrderItem
                        {
                            OrderId = order.Id,
                            MedicineId = Random.Shared.Next(1, 100),
                            MedicineName = medicine.Name,
                            Specification = medicine.Spec,
                            UnitPrice = medicine.Price,
                            Quantity = quantity,
                            Subtotal = subtotal,
                            CreatedAt = order.CreatedAt
                        };

                        orderItems.Add(orderItem);
                    }
                }

                // 保存订单商品
                await _context.MedicalOrderItem.AddRangeAsync(orderItems);
                await _context.SaveChangesAsync();

                // 生成物流追踪数据（仅对已发货的订单）
                foreach (var order in orders.Where(o => o.Status >= 4))
                {
                    var trackingCount = Random.Shared.Next(3, 6); // 3-5条物流记录
                    var baseTime = order.CreatedAt ?? DateTime.Now;

                    for (int k = 0; k < trackingCount; k++)
                    {
                        var logisticsStatus = k switch
                        {
                            0 => 0, // 待发货
                            1 => 1, // 已发货
                            2 => 2, // 运输中
                            _ => 3  // 已签收
                        };

                        var tracking = new MedicalOrderLogisticsTracking
                        {
                            OrderId = order.Id,
                            TrackingNumber = order.TrackingNumber,
                            LogisticsCompany = order.LogisticsCompany,
                            Location = GetLocationByStatus(logisticsStatus),
                            Status = logisticsStatus,
                            UpdateTime = baseTime.AddDays(k),
                            ExtraInfo = GetExtraInfoByStatus(logisticsStatus)
                        };

                        logisticsTracking.Add(tracking);
                    }
                }

                // 保存物流追踪数据
                if (logisticsTracking.Any())
                {
                    await _context.MedicalOrderLogisticsTracking.AddRangeAsync(logisticsTracking);
                    await _context.SaveChangesAsync();
                }

                _logger.LogInformation("药品订单数据初始化完成，共创建 {OrderCount} 个订单，{ItemCount} 个订单商品，{TrackingCount} 条物流记录",
                    orders.Count, orderItems.Count, logisticsTracking.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化药品订单数据失败");
                throw;
            }
        }

        private string GetLocationByStatus(int status)
        {
            return status switch
            {
                0 => "北京市朝阳区仓库",
                1 => "北京市朝阳区配送中心",
                2 => "北京市海淀区中转站",
                3 => "北京市朝阳区收货地址",
                _ => "未知位置"
            };
        }

        private string GetExtraInfoByStatus(int status)
        {
            return status switch
            {
                0 => "订单已确认，准备发货",
                1 => "包裹已发出，正在配送中",
                2 => "包裹运输中，预计明天送达",
                3 => "包裹已送达，请及时签收",
                _ => "物流信息更新"
            };
        }
    }
} 